const { winston, createLogger, transports, format } = require("winston");

const wlogger = createLogger({
    transports: [
        new transports.Console({
            format: format.combine(
                format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
                customConsoleFormat()
            ),
        }),
        new transports.File({ filename: "error.log", level: "error" }),
        new transports.File({ filename: "combined.log" }),
    ],
    format: format.combine(
        format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
        format.json()
    ),
});

function customConsoleFormat() {
    return format.printf(({ timestamp, level, message }) => {
        return `[${timestamp}] ${message}`;
    });
}

function stringify(value, indent = 0) {
    if (typeof value === "object" && value !== null) {
        if (Array.isArray(value)) {
            const items = value.map((item) => stringify(item, indent + 2));
            return `[${items.join(", ")}]`;
        } else {
            const properties = Object.entries(value).map(([key, val]) => {
                const formattedValue = stringify(val, indent + 2);
                return `${key}: ${formattedValue}`;
            });
            return `{${"".repeat(indent + 2)}${properties.join(`,${" ".repeat(indent + 2)}`)}${"".repeat(indent)}}`;
        }
    } else {
        return JSON.stringify(value);
    }
}

function toString(...args) {
    return args
        .map((arg) => {
            if (typeof arg === "object" && arg !== null) {
                return stringify(arg);
            } else {
                return arg;
            }
        })
        .join(" ");
}

const info = function (...args) {
    //console.log(...args);
    const info = toString(...args);
    wlogger.info(info);
};

const error = function (...args) {
    //console.log(...args);
    const info = toString(...args);
    wlogger.error(info);
};

const logger = { info, error };
module.exports = logger;
